<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<title>dojox.Grid with Dojo.Data via binding</title>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></meta>
	<style type="text/css">
		@import "../../../dojo/resources/dojo.css";
		@import "../_grid/tundraGrid.css";
		
		#grid, #grid2 {
			width: 65em;
			height: 25em;
			padding: 1px;
		}
	</style>
	<script type="text/javascript" src="../../../dojo/dojo.js" 
		djConfig="isDebug: true, debugAtAllCosts: false, parseOnLoad: true"></script>
	<script type="text/javascript">
		dojo.require("dojox.grid.Grid");
		dojo.require("dojox.grid._data.model");
		dojo.require("dojox.rpc.Service");
		dojo.require("dojox.data.PersevereRestStore");
		dojo.require("dojo.parser");
	</script>
	<script type="text/javascript">
		function getRow(inRowIndex){
			return ' ' + inRowIndex;
		}
		
		
		var layout = [
			// view 0
			{ type: 'dojox.GridRowView', width: '20px' },
			// view 2
			{ 
				defaultCell: { width: 8, editor: dojox.grid.editors.Input, styles: 'text-align: right;'  },
				cells: [[
				{editor:null },
				{ }
			]]}
		];
		var persevereServices = new dojox.rpc.Service("/persevere/SMD"); // just connect to the auto-generated SMD from persevere
		dynaStore = new dojox.data.PersevereRestStore({service:persevereServices.dyna}); // and create a store for it
		dataModel = new dojox.grid.data.DojoData(null,null,{rowsPerPage:12,store:dynaStore,query:"46.customers",clientSort:true});
		
		removeItem = function() {
			// Removes the first item in the model from the store
			// Grid should reflect removal of the first item and items should be re-indexed

			// need to specify the parent because the dynaStore is hierarchical and the grid model will 
			// call newItem without any info who the parent
			dynaStore.parentId="46.customers";			
			dynaStore.deleteItem(dataModel.data[0].__dojo_data_item);
		}
		
		var i = 0;
		addItem = function() {
			// need to specify the parent because the dynaStore is hierarchical and the grid model will 
			// call newItem without any info who the parent
			dynaStore.parentId="46.customers";
			grid.addRow({firstName: "firstName", lastName: "lastName",created:new Date});
		}
		addItemToStore = function() {
			// Adds a new item to the store
			// Grid should reflect the new item.
			dynaStore.newItem({firstName: "firstName", lastName: "lastName",created:new Date});
		}
		removeProperty = function() {
			var selected = grid.selection.getSelected();
			for (var i = 0; i < selected.length;i++) {
				dynaStore.unsetAttribute(dataModel.getRow(selected[i]).__dojo_data_item,columns[grid.focus.cell.fieldIndex].field);
			}
		}
		addProperty = function() {
			var selected = grid.selection.getSelected();
			if (selected.length != 1)
				return alert("You must select one item");
			var item = dataModel.getRow(selected[0]).__dojo_data_item;
			console.log('select index ' + selected[0]);
			console.log('row ' , item);
			var key = prompt("What would you like to name the new property?","property");
			//var valueType = prompt("What type of value would you like?","string");
			dynaStore.setValue(item,key,"new value");
			dataModel.findAdditionFields([item],columns);
		}
		refresh = function() {
			grid.refresh();
		}
		dataModel.findAdditionFields = function(items,columns) {
			var m = this.fields._nameMaps || (this.fields._nameMaps = {}); 
			var fields = this.fields._fields || (this.fields._fields = []);
			for (var i = 0; i<items.length; i++) {
				var item = items[i];
				for (var j in item) {
					if (j != 'id' && j != '_id' && typeof m[j] != 'number') { // if we have not accounted for this property yet
						m[fields.length+".idx"] = j;
						m[j] = fields.length;
						fields.push({name: j, key: j});
						columns.push({field:j});
					}
				}
			}
			// console.debug("new fields:", fields);
			layout[1].cells[0] = columns;
			grid.setStructure(layout);
			this.fields.set(fields);
			this.notify("FieldsChange");
		}
		dataModel.processRows = function(items,request) { 
		// this overwrites the processRows function, so that the columns be can be 
		// dynamically generated based on the data. Real applications will probably
		// be content with a more static generation of columns (like actually
		// manually typing them out in the layout).
			columns = [];
			this.findAdditionFields(items,columns);
			// do the feault behavior now
			return dojox.grid.data.DojoData.prototype.processRows.apply(this,arguments);
		} 
		dataModel._setupFields= function(dataItem){
		// this is called by the super impl of processRows, but we don't want it to do anything
		}
		
		
	</script>
</head>
<body class="tundra">
	<h5>dojox.Grid using interactive PersevereRestStore</h5>
	<div id="controls">
		<button onclick="dynaStore.save()">Save</button>
		<button onclick="dynaStore.revert()">Revert</button>
		<button onclick="refresh()">Refresh</button>&nbsp;&nbsp;&nbsp;
		<button onclick="addItem()">Add</button>
		<button onclick="grid.removeSelectedRows()">Remove</button>&nbsp;&nbsp;&nbsp;
		<button onclick="addProperty()">Add Property</button>
		<button onclick="removeProperty()">Remove Property</button>
<!-- Testing buttons (not so good for demos) <button onclick="removeItem()">Remove (Store)</button>
		<button onclick="addItemToStore()">Add (Store)</button>&nbsp;&nbsp;&nbsp;
		<button onclick="grid.edit.apply()">Apply</button>
		<button onclick="grid.edit.cancel()">Cancel</button>&nbsp;&nbsp;&nbsp; -->		
	</div>

	<div id="grid" jsId="grid" dojoType="dojox.Grid" elasticView="2" 
		model="dataModel" structure="layout">
	</div>
</body>
</html>
